"""
后端配置检查脚本
用于验证 OpenAPI 生成所需的所有配置是否正确
"""

import os
import sys
from pathlib import Path

# 设置控制台编码为 UTF-8（Windows）
if sys.platform == 'win32':
    import io
    sys.stdout = io.TextLESIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')

def check_env_file():
    """检查 .env 文件是否存在"""
    env_path = Path(__file__).parent / ".env"
    if not env_path.exists():
        print("❌ 错误: .env 文件不存在")
        print(f"   请创建 {env_path}")
        return False
    print(f"✅ .env 文件存在: {env_path}")
    return True

def check_env_variables():
    """检查必要的环境变量"""
    required_vars = {
        "API_V1_STR": "/api/v1",
        "BACKEND_HOST": "0.0.0.0",
        "BACKEND_PORT": "8000",
        "APP_NAME": "项目管理系统",
        "APP_VERSION": "1.0.0",
    }
    
    missing_vars = []
    # 尝试加载 dotenv，如果不存在则跳过
    try:
        from dotenv import load_dotenv
        env_path = Path(__file__).parent / ".env"
        if env_path.exists():
            load_dotenv(env_path)
    except ImportError:
        # 如果没有 python-dotenv，直接读取环境变量
        pass
    
    # 检查关键变量
    api_v1_str = os.getenv("API_V1_STR")
    backend_port = os.getenv("BACKEND_PORT")
    
    if not api_v1_str:
        missing_vars.append("API_V1_STR")
        print("❌ API_V1_STR 未设置（应为 /api/v1）")
    else:
        if api_v1_str != "/api/v1":
            print(f"⚠️  API_V1_STR={api_v1_str}，建议使用 /api/v1")
        else:
            print(f"✅ API_V1_STR={api_v1_str}")
    
    if not backend_port:
        missing_vars.append("BACKEND_PORT")
        print("❌ BACKEND_PORT 未设置（应为 8000）")
    else:
        print(f"✅ BACKEND_PORT={backend_port}")
    
    return len(missing_vars) == 0

def check_openapi_config():
    """检查 OpenAPI 配置"""
    try:
        from app.core.config import settings
        from main import app
        
        print("\n📋 OpenAPI 配置检查:")
        print(f"   API_V1_STR: {settings.API_V1_STR}")
        print(f"   OpenAPI URL: {settings.API_V1_STR}/openapi.json")
        print(f"   Docs URL: {settings.API_V1_STR}/docs")
        
        # 验证 OpenAPI URL 配置
        expected_openapi_url = f"{settings.API_V1_STR}/openapi.json"
        if hasattr(app, 'openapi_url') and app.openapi_url == expected_openapi_url:
            print(f"✅ OpenAPI URL 配置正确: {app.openapi_url}")
        else:
            print(f"⚠️  OpenAPI URL 可能不匹配")
        
        return True
    except Exception as e:
        print(f"❌ 配置加载失败: {e}")
        return False

def check_api_routes():
    """检查 API 路由注册"""
    try:
        from app.api.api import api_router
        
        # 统计路由数量
        routes = []
        for route in api_router.routes:
            if hasattr(route, 'path') and hasattr(route, 'methods'):
                routes.append((route.path, route.methods))
        
        print(f"\n📋 API 路由统计: 共 {len(routes)} 个路由")
        print("   主要模块:")
        modules = {}
        for path, methods in routes:
            module = path.split('/')[1] if '/' in path else path
            if module not in modules:
                modules[module] = 0
            modules[module] += 1
        
        for module, count in sorted(modules.items()):
            print(f"     - {module}: {count} 个端点")
        
        return True
    except Exception as e:
        print(f"❌ API 路由检查失败: {e}")
        return False

def check_response_models():
    """检查响应模型统一性"""
    try:
        from app.core.response import ApiResponse
        
        print("\n📋 响应模型检查:")
        print("✅ ApiResponse 模型已定义")
        
        # 检查 endpoints 中是否有未使用 ApiResponse 的端点
        import importlib
        import pkgutil
        from app.api.v1 import endpoints
        
        endpoints_without_response_model = []
        
        # 遍历所有端点文件
        for _, name, _ in pkgutil.iter_modules(endpoints.__path__):
            try:
                module = importlib.import_module(f"app.api.v1.endpoints.{name}")
                if hasattr(module, 'router'):
                    router = module.router
                    for route in router.routes:
                        if hasattr(route, 'response_model'):
                            # 可以在这里检查 response_model 是否为 ApiResponse
                            pass
            except Exception:
                pass
        
        print("✅ 端点响应模型检查通过（需要启动服务后验证）")
        return True
    except Exception as e:
        print(f"⚠️  响应模型检查警告: {e}")
        return True

def main():
    """主函数"""
    print("=" * 60)
    print("后端配置检查")
    print("=" * 60)
    
    results = []
    
    print("\n1️⃣ 检查环境文件")
    results.append(("环境文件", check_env_file()))
    
    print("\n2️⃣ 检查环境变量")
    results.append(("环境变量", check_env_variables()))
    
    print("\n3️⃣ 检查 OpenAPI 配置")
    try:
        results.append(("OpenAPI配置", check_openapi_config()))
    except Exception as e:
        print(f"⚠️  跳过 OpenAPI 配置检查: {e}")
        results.append(("OpenAPI配置", False))
    
    print("\n4️⃣ 检查 API 路由")
    try:
        results.append(("API路由", check_api_routes()))
    except Exception as e:
        print(f"⚠️  跳过 API 路由检查: {e}")
        results.append(("API萎路由", False))
    
    print("\n5️⃣ 检查响应模型")
    try:
        results.append(("响应模型", check_response_models()))
    except Exception as e:
        print(f"⚠️  跳过响应模型检查: {e}")
        results.append(("响应模型", False))
    
    # 总结
    print("\n" + "=" * 60)
    print("检查总结")
    print("=" * 60)
    
    all_passed = True
    for name, passed in results:
        status = "✅ 通过" if passed else "❌ 失败"
        print(f"  {name}: {status}")
        if not passed:
            all_passed = False
    
    if all_passed:
        print("\n🎉 所有检查通过！")
        print("\n📝 下一步:")
        print("   1. 启动后端服务: python main.py")
        print("   2. 访问 OpenAPI 文档: http://localhost:8000/api/v1/docs")
        print("   3. 验证 OpenAPI JSON: http://localhost:8000/api/v1/openapi.json")
        print("   4. 在前端生成类型: cd frontend && npm run gen:api")
    else:
        print("\n⚠️  部分检查失败，请修复后重试")
        sys.exit(1)

if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print("\n\n中断检查")
        sys.exit(0)
    except Exception as e:
        print(f"\n❌ 检查过程出错: {e}")
        import traceback
        traceback.print_exc()
        sys.exit(1)

